package com.wx.task.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 自定义累加器
 * 利用原子类，无所化执行
 * CAS操作 依据为cpu原子指令
 *
 * @author wang.xun
 * @date 2023/07/31
 */
@Slf4j
public class MyCount {
    private final AtomicLong count = new AtomicLong();

    void addOne() {
        count.incrementAndGet();
    }
    long getCount(){
        return count.get();
    }



    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(100);
        CountDownLatch countDownLatch = new CountDownLatch(1_000_000);
        MyCount count = new MyCount();

        for (int i = 0; i < 1_000_000;i++){

            es.execute(()->{
                count.addOne();
                countDownLatch.countDown();
            });
        }

        try {
            countDownLatch.await();
            es.shutdownNow();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("myCount 计数器最后的值 :{}",count.getCount());


    }
}
